package com.gocoolmall.auth.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gocoolmall.auth.feign.MemberFeignService;
import com.gocoolmall.auth.vo.SocialUser;
import com.gocoolmall.common.utils.HttpUtils;
import com.gocoolmall.common.utils.R;
import com.gocoolmall.common.vo.MemberRespVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * 处理社交登录请求
 */

@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code , HttpSession session, HttpServletResponse sessionResponse) throws Exception {
        //1、根据code换取accessToken
        HashMap<String , String> map= new HashMap<>();
        map.put("client_id","1137950859");
        map.put("client_secret","6bddd0e19e5f7b54f7d108e1c13242f9");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gocoolmall.com/oauth2.0/weibo/success");
        map.put("code",code);
        HashMap<String, String> headers = new HashMap<>();
//        headers.put("Authorization", "GOCOOLMALL " + code);
        HttpResponse response = null;
        try {
            response = HttpUtils.doPost(
                    "https://api.weibo.com", "/oauth2/access_token",
                    "post", headers,
                    null , map);
            System.out.println("response:返回"+response.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //2、处理
        if (response.getStatusLine().getStatusCode() ==200){
            //获取response的body
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            System.out.println("获取成功"+socialUser);
            //知道那是哪个社交用户
            //1）、当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个会员信息账号，以后这个社交账号就对应指定的会员）
            //登录或者注册这个社交用户
            R oauthlogin = null;
            try {
                oauthlogin = memberFeignService.oauthlogin(socialUser);
                System.out.println("调用登录注册返回："+oauthlogin.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (oauthlogin.getCode() == 0){
                MemberRespVo data = oauthlogin.getDate("date", new TypeReference<MemberRespVo>(){
                });
                System.out.println("登录成功，用户信息date:"+data);
                log.info("登录成,用户信息：{}",data);
                //TODO 1、默认发的令牌， session=dsajkdjl.作用域：（解决子域session共享问题）
                //TODO 2、使用JSON的序列化方式来序列化对象数据到redis中
                session.setAttribute("loginUser", data);
                //1.第一次使用session，命令浏览器保存卡，JSESSIONID这个cookie
                //以后浏览器访问哪个网站就会带上这个网站的cookie
                //子域之间： gocoolmall.com auth.gocoolmall.com order.gocoolmall.com
                //发卡的时候（指定域名为父域名），即使式子域系统发的卡，也能让父域直接使用

//                new Cookie("JESESSONID","adfewfa").setDomain("");
//                sessionResponse.addCookie(new Cookie("JESESSONID","adfewfa"));
            }
            return "redirect:http://gocoolmall.com";
        }else {
            return "redirect:http://auth.gocoolmall.com/login.html";
        }
    }
}
